<template>
  <transition
    class="fly-ball"
    @before-enter="beforeEnter"
    @enter="enter"
    @after-enter="afterEnter"
  >
    <div class="ball" v-show="isShow" ref="ball">{{ num }}</div>
  </transition>
</template>
<script>
export default {
  name: "flyBall",
  props: {
    num: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
       delay: 1, //单位秒
    };
  },
  computed: {
    isShow() {
      return this.$store.state.isShowBall;
    },
  },
  methods: {
    beforeEnter(el) {
      el.style.transform = "translate(0, 0)";
    },
    enter(el, done) {
      el.offsetWidth; //用于刷新动画，没有的话没效果
      const ballBCR = this.$refs.ball.getBoundingClientRect();
      const cartBCR = document.getElementById("cart").getBoundingClientRect();
      const xDist = cartBCR.left - ballBCR.left;
      const yDist = cartBCR.top - ballBCR.top;
      el.style.transform = `translate(${xDist}px, ${yDist}px)`;
      el.style.transition = `all ${this.delay}s cubic-bezier(.4,-0.3,1,.68)`;
      done(); //必须加，执行的是after里边的代码
    },
    afterEnter(el) {
      this.$store.commit("changeShowBall", false);
      setTimeout(() => {
        this.$store.commit("changeAddFinish", true);
      }, (this.delay+.5) * 1000);
    },
  },
};
</script>
<style lang="scss" scoped>
.ball {
  position: absolute;
  color: #fff;
  height: 50px;
  width: 50px;
  font-size: 30px;
  font-weight: bold;
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
  background: $theme-color;
  z-index: 1000;
}
</style>